#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

BOINCEXE_NAME=boinc_client
BOINCDIR=/opt/boinc
PRESETDIR=/usr/share/boinc
BOINCUSR=boinc
BOINCEXE_OPTS="--check_all_logins --redirectio --dir $BOINCDIR"
PID_FILE="/var/run/$BOINCEXE_NAME.pid"

start_service() {
   # First check that BOINCDIR exists
   if ! [ -d "$BOINCDIR" ]; then
      if ! mkdir -p $BOINCDIR 2>/dev/null ; then
         echo "ERROR: $BOINCDIR doesn't exist and couldn't be created"
         return 1
      fi
   fi

   # adjust some presettings if necessary
   for f in global_prefs_override.xml remote_hosts.cfg; do
      if ! [ -f $BOINCDIR/$f ]; then
         cp $PRESETDIR/$f $BOINCDIR
      fi
   done

   # and ensure it is accessible by boinc
   BOINCDIR_OWNER="$(ls -ld $BOINCDIR | awk '{print $3}')"
   if [ "$BOINCUSR" != "$BOINCDIR_OWNER" ] ; then
      chown -R $BOINCUSR:$BOINCUSR $BOINCDIR
      BOINCDIR_OWNER="$(ls -ld $BOINCDIR | awk '{print $3}')"

      if [ "$BOINCUSR" != "$BOINCDIR_OWNER" ] ; then
         echo "User boinc can't access $BOINC_DIR"
         return 3
      fi
   fi

   # now use procd to start boinc
   procd_open_instance $BOINCEXE_NAME

   procd_set_param command $(which $BOINCEXE_NAME)
   procd_append_param command $BOINCEXE_OPTS
   procd_set_param user $BOINCUSR
   procd_set_param limits core="unlimited"
   procd_set_param stdout 1
   procd_set_param stderr 1
   procd_set_param pidfile $PID_FILE

   procd_add_jail $BOINCEXE_NAME log requirejail
   procd_add_jail_mount /etc/TZ
   procd_add_jail_mount /proc/cpuinfo /proc/meminfo
   procd_add_jail_mount /etc/ssl/certs/ca-certificates.crt
   procd_add_jail_mount $PRESETDIR
   procd_add_jail_mount_rw $BOINCDIR

   procd_close_instance
}
